import re
from datetime import datetime
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.common.by import By
from openpyxl import Workbook


class HouseInfo:

    def __init__(self) -> None:

        option = Options()
        option.add_argument('--ignore-certificate-errors')
        option.add_experimental_option('excludeSwitches', ['enable-automation'])
        option.add_argument('--disable-blink-features=AutomationControlled')
        prefs = {'credentials_enable_service': False, 'profile.password_manager_enabled': False}
        option.add_experimental_option('prefs', prefs)
        self.driver = webdriver.Chrome(options=option)
        self.driver.implicitly_wait(20)
        # 最大化
        self.driver.maximize_window()
        self.BaseUrl = "https://fc.shfq.com/"
        self.workbook = Workbook()
        self.sheet = self.workbook.active
        self.sheet['A1'] = "房源编号"
        self.sheet['B1'] = "小区名"
        self.sheet['C1'] = "标题"
        self.sheet['D1'] = "售价"
        self.sheet['E1'] = "单价"
        self.sheet['F1'] = "户型"
        self.sheet['G1'] = "建筑面积"
        self.sheet['H1'] = "朝向"
        self.sheet['I1'] = "楼层"
        self.sheet['J1'] = "总楼高"
        self.sheet['K1'] = "装修"
        self.sheet['L1'] = "销售"
        self.sheet['M1'] = "销售电话"
        self.sheet['N1'] = "更新时间"
        self.sheet['O1'] = "网址"


    def getHtml(self,page=1):
        url = "resoldhome/esf/list?kw='富园'&type=1&page={}".format(page)
        self.driver.get(self.BaseUrl + url)
        house_items = self.driver.find_elements(By.XPATH, '//li[@class="item clearfix"]')
        return house_items

    def parseHtml(self):
        page = 0
        UrlList = []
        while True:
            page += 1
            elements = self.getHtml(page=page)
            if elements:
                for element in elements:
                    houseUrl = element.find_element(By.XPATH, './/p[@class="title"]/a').get_attribute("href")
                    UrlList.append(houseUrl)
            else:
                 break
        return UrlList
    
    def parseDetail(self):
        houseUrlList = self.parseHtml()
        row = 2
        for url in houseUrlList:
            self.driver.get(url)
            try:
                # 房源编号
                ListingNumber = self.driver.find_element(By.XPATH, './/span[@class="time"][1]').text
                ListNumber = re.findall(r'\d+', ListingNumber)[0]
                # 发布时间
                UpdateTime = self.driver.find_element(By.XPATH, './/span[@class="time"][2]').text.split("：")[1]
                # 标题
                title = self.driver.find_element(By.CLASS_NAME, 'title').text
                # 售价
                sellingPrice = self.driver.find_element(By.CLASS_NAME, 'detailInfo-price_big').text
                # 户型
                houseType = self.driver.find_element(By.XPATH, '//tbody/tr[1]/td[1]/div[@class="detailInfo-p1"]').text
                # 建筑面积约
                grossFloorArea= self.driver.find_element(By.XPATH, '//tbody/tr[1]/td[2]/div[@class="detailInfo-p1"]').text
                # 单价
                unitPrice = self.driver.find_element(By.XPATH, '//tbody/tr[1]/td[3]/div[@class="detailInfo-p1"]').text.split("/")[0]
                # 朝向
                orientation = self.driver.find_element(By.XPATH, '//tbody/tr[2]/td[1]/div[@class="detailInfo-p1"]').text
                # 楼层
                floor = self.driver.find_element(By.XPATH, '//tbody/tr[2]/td[2]/div[@class="detailInfo-p1"]').text
                # 总楼高
                totalFloor = self.driver.find_element(By.XPATH, '//tbody/tr[2]/td[2]/div[@class="detailInfo-p2"]').text
                # 装修
                fitment = self.driver.find_element(By.XPATH, '//tbody/tr[2]/td[3]/div[@class="detailInfo-p1"]').text
                # 小区名
                cellName = self.driver.find_element(By.XPATH, '//a[@clas="addr"]').text.replace("(","")
                # 销售
                SalesName = self.driver.find_element(By.CLASS_NAME, 'detailjjr-name').text
                # 销售电话
                SalesPhoneNumber = self.driver.find_element(By.CLASS_NAME, 'detailjjr-tel').text
                self.sheet.cell(row, 1, ListNumber)
                self.sheet.cell(row, 2, cellName)
                self.sheet.cell(row, 3, title)
                self.sheet.cell(row, 4, sellingPrice)
                self.sheet.cell(row, 5, unitPrice)
                self.sheet.cell(row, 6, houseType)
                self.sheet.cell(row, 7, grossFloorArea)
                self.sheet.cell(row, 8, orientation)
                self.sheet.cell(row, 9, floor)
                self.sheet.cell(row, 10, totalFloor)
                self.sheet.cell(row, 11, fitment)
                self.sheet.cell(row, 12, SalesName)
                self.sheet.cell(row, 13, SalesPhoneNumber)
                self.sheet.cell(row, 14, UpdateTime)
                cell = self.sheet.cell(row, 15)
                cell.value = "点击查看详情"
                cell.hyperlink = url
                row += 1
            except Exception:
                continue
        current_time = datetime.now().strftime("%Y-%m-%d")
        self.workbook.save(f"./result/{current_time}泗洪富园二手房交易信息.xlsx")
        self.driver.quit()


if __name__ == "__main__":
    HouseInfo().parseDetail()
